<template>
  <div>
    <div class="home" id="box" style="overflow: hidden; position: relative">
      <div id="demo">集群：位置是不固定的，需要由主机内容撑开，接口有几个数组创建几个集群，每遍历一次数组创建一个集群dom节点，获取节点xy轴位置，<br>
        主机：集群数组里面有几个对象就遍历几项，每遍历一次创建一个dom节点(或者给一个盒子宽高)，获取节点xy轴位置，再把数据放到节点里面，<br>
        主机height，width是固定的，集群的height,width根据主机内容撑开有最大宽高限制， <br>
      </div>

      <div id="wheel_div" style="position: absolute; left: 0; top: 0">
        <canvas id="myCanvas" width="1500" height="1178"></canvas>
        <server v-for="item of hostList" :hostList="item" :key="item.id"></server>
      </div>
    </div>
  </div>
</template>

<script>
const server = () => import("./Server.vue");
import { fabric } from "fabric";

export default {
  name: "Home",
  components: {
    // HelloWorld,
    server,
  },

  data () {
    return {
      data: [
        [
          {
            id: "LBS-1",
            name: "负载均衡服务器LBS-1",
            Internet: "1.99.165.58 1",
            status: "normal",
            ascription: "col1",
            x: 500,
            y: 56,
            width: 154,
            height: 110,
          },
          {
            id: "LBS-2",
            name: "负载均衡服务器LBS-2",
            intranet: "172.26.137.195",
            status: "normal",
            ascription: "col1",
            x: 736,
            y: 56,
            width: 154,
            height: 110,
          },
          {
            id: "port-3",
            name: "负载均衡服务器LBS-2",
            Internet: "3.99.135.136",
            intranet: "172.26.137.195",
            status: "normal",
            ascription: "col1",
            x: 500,
            y: 188,
            width: 154,
            height: 110,
          },
        ],
        [
          {
            id: "AP4",
            name: "负载均衡服务器LBS-2",
            Internet: "4.99.135.136",
            intranet: "172.26.137.195",
            status: "normal",
            ascription: "col2",
            x: 736,
            y: 188,
          },
          {
            id: "API5",
            name: "负载均衡服务器LBS-2",
            Internet: "55.99.135.136",
            intranet: "172.26.137.195",
            status: "normal",
            ascription: "col2",
            x: 618,
            y: 255,
          },
        ],
      ],
      colonyList: [], //集群列表
      hostList: "", //主机列表
      left: 30,
      top: 36,
      width: 1500,
      height: 1178,
      wid: 154, //单个主机宽度
      hei: 110,
      colonyWidth: 200, //单个集群宽度
      colonyHeight: 200,
      maxwid: this.wid * 6, //单个集群最大宽度
      maxhei: this.hei * 5,
    };
  },
  mounted () {
    // var demo = document.getElementById("demo");
    // this.getXY(demo);
    this.$nextTick(function () {
      this.colony();
      // this.initContainer();
      this.pan();
      this.zoom();
    });
  },
  // 监听属性 类似于data概念
  computed: {
    // width: function () {
    //   return console.log(this.hostList.width + "px");
    // },
    // height: function () {
    //   return this.hostList.height + "px";
    // },
  },
  methods: {
    colony () {
      const canvas = new fabric.Canvas("myCanvas");
      this.data.forEach((item, index) => {
        console.log(index);
        this.colonyList = item;

        this.colonyWidth = item.length * this.wid; //集群宽高
        this.colonyHeight = item.length / 6 == 0 ? item.length * this.hei : Math.ceil(item.length / 6) * this.hei;
        console.log(this.colonyWidth);


        let rect3 = this.drawRect({
          left: index == 0 ? 0 : this.colonyWidth,
          top: index == 0 ? 0 : this.colonyHeight,
          width: this.colonyWidth,
          height: this.colonyHeight,
        });
        canvas.add(rect3);
        item.forEach((element) => {
          // console.log(element);
        });
      });
    },

    initContainer () {
      const canvas = new fabric.Canvas("myCanvas");
      // 大框
      let rect = this.drawRect({
        left: this.left,
        top: 36,
        width: 1100,
        height: 580,
      });
      canvas.add(rect); //添加图形至canvas画布
      // 小框
      let rect2 = this.drawRect({
        left: 931,
        top: 298,
        width: 385,
        height: 200,
      });
      canvas.add(rect2);
      for (let item of this.colonyList) {
        let rect = this.drawRect(item);
        canvas.add(rect);
      }

      let lineData = [
        [580, 140, 795, 255], // 1-4
        [580, 250, 795, 140], // 2-3
        [580, 270, 1156, 603], // 3-21
        [780, 267, 100, 650], // 4-14
        [458, 338, 680, 469], //66-10
        [90, 390, 890, 860], //77-21
        [300, 400, 95, 520], //88-12
        [900, 749, 710, 866], //18-20
        [784, 680, 588, 792], // 16-19
        [661, 611, 464, 724], // 22-17
        [540, 540, 440, 595], // 13
        [279, 656, 190, 600], // 15
        [903, 458, 1002, 400], // 99
        [1033, 531, 1139, 472], //11
        // [0, 0, 1, 1],
      ];
      for (let item of lineData) {
        let line = this.makeLine(item);
        canvas.add(line); // 将线条添加到canvas画布上
      }
      var Line = this.makeLine({});
      canvas.add(Line);
    },
    drawRect (data) {
      //绘制矩形边框
      // console.log("zzzzzzzzzzzzzzzzzz", data);
      return new fabric.Rect({
        left: data.left,
        top: data.top,
        fill: "rgba(75, 138, 215, .1)", //背景颜色
        stroke: "#213973", //边框颜色
        width: data.width,
        height: data.height,
        // rx: 30,
        // ry: 30,
        // angle: 30.1,
        // skewX: -29, //对象 x 轴上的倾斜角度（以度为单位）
        // scaleX: 1, //对象比例因子（水平）
        // allowTouchScrolling: true,
      });
    },
    makeLine (coords) {
      // 绘制线段连线路径
      return new fabric.Line(coords, {
        stroke: "#1870C7",
        strokeWidth: 1,
        selectable: false,
        evented: false,
      });
    },
    // 拖拽
    zoom () {
      var drag = document.getElementById("wheel_div");
      // 点击某物体时，用drag对象即可，move和up是全局区域，
      // 也就是整个文档通用，应该使用document对象而不是drag对象(否则，采用drag对象时物体只能往右方或下方移动)
      drag.onmousedown = function (event) {
        var event = event || window.event; //兼容IE浏览器
        //  鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
        var diffX = event.pageX - drag.offsetLeft;
        var diffY = event.pageY - drag.offsetTop;
        if (typeof drag.setCapture !== "undefined") {
          drag.setCapture();
        }
        document.onmousemove = function (event) {
          var event = event || window.event;
          var moveX = event.pageX - diffX;
          var moveY = event.pageY - diffY;
          drag.style.left = moveX + "px";
          drag.style.top = moveY + "px";
          // 限制在父元素区域内
          moveX < -drag.offsetWidth / 2
            ? (drag.style.left = -drag.offsetWidth / 2 + "px")
            : "";
          moveX > drag.offsetWidth / 2
            ? (drag.style.left = drag.offsetWidth / 2 + "px")
            : "";
          moveY < -drag.offsetHeight / 2
            ? (drag.style.top = -drag.offsetHeight / 2 + "px")
            : "";
          moveY > drag.offsetHeight / 2
            ? (drag.style.top = drag.offsetHeight / 2 + "px")
            : "";
        };
        document.onmouseup = function (event) {
          this.onmousemove = null;
          this.onmouseup = null;
          //修复低版本ie bug
          if (typeof drag.releaseCapture != "undefined") {
            drag.releaseCapture();
          }
        };
      };
    },
    // 缩放
    pan () {
      let drag = document.getElementById("wheel_div");
      let scal = 1;
      let maxScal = 1.2; // 最大缩放
      let minScal = 0.7;
      function onMouseWheel (ev) {
        /*当鼠标滚轮事件发生时，执行一些操作*/
        var ev = ev || window.event;
        var down = true; // 定义一个标志，当滚轮向下滚时，执行一些操作
        down = ev.wheelDelta ? ev.wheelDelta < 0 : ev.detail > 0;
        if (down) {
          scal <= minScal ? "" : (scal = (parseFloat(scal) - 0.06).toFixed(2));
          drag.style.transform = "scale(" + scal + ")"; //scale()在这里要使用拼接的方式才能生效。
          // drag.style.transformOrigin = "0 0"; // 已canvas为原点缩放
        } else {
          scal >= maxScal ? "" : (scal = (parseFloat(scal) + 0.06).toFixed(2));
          drag.style.transform = "scale(" + scal + ")";
        }
        if (ev.preventDefault) {
          /*FF 和 Chrome*/
          ev.preventDefault(); // 阻止默认事件
        }
        return false;
      }
      addEvent(box, "mousewheel", onMouseWheel);
      addEvent(box, "DOMMouseScroll", onMouseWheel);
      function addEvent (obj, xEvent, fn) {
        if (obj.attachEvent) {
          obj.attachEvent("on" + xEvent, fn);
        } else {
          obj.addEventListener(xEvent, fn, false);
        }
      }
    },

    //获取xy坐标
    getXY (obj) {
      let x = 0,
        y = 0;
      if (obj.getBoundingClientRect) {
        var box = obj.getBoundingClientRect();
        var D = document.documentElement;
        x =
          box.left +
          Math.max(D.scrollLeft, document.body.scrollLeft) -
          D.clientLeft;
        y =
          box.top +
          Math.max(D.scrollTop, document.body.scrollTop) -
          D.clientTop;
      } else {
        for (
          ;
          obj != document.body;
          x += obj.offsetLeft, y += obj.offsetTop, obj = obj.offsetParent
        ) { }
      }
      // return console.log("x", x, "y", y);
    },
  },
};
</script>

<style lang="less" scoped>
.board-div {
  display: flex;
  color: #fff;
  margin: 16px;
}
.div1 {
  width: 100px;
}
#demo {
  width: 100%;
  height: 800px;
  border: 1px solid;
  margin: 0 auto;
}
.home {
  flex: 1;
}

#wheel_div {
  position: relative;
  width: 1264px;
  height: 984px;
  border: 2px solid #3368b8;
  text-align: center;
  // padding: 15px;
}
#myCanvas {
  z-index: 1;
}
</style> 
